package com.njlime.sys.service;

import com.njlime.core.exception.BusinessException;
import com.njlime.core.helper.GlobalValue;
import com.njlime.core.helper.PageBean;
import com.njlime.core.utils.StringUtil;
import com.njlime.sys.entities.Role;
import com.njlime.sys.entities.Unit;
import com.njlime.sys.repository.RoleDao;
import com.njlime.sys.security.util.CacheUtils;
import com.njlime.sys.security.util.UserUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Dean on 2017-7-19.
 */
@Service
@Transactional(readOnly = true)
public class RoleService {

    @Resource
    private RoleDao roleDao;
    @Resource
    private UnitService unitService;

    /**
     * 分页获取角色数据列表
     *
     * @param pageBean
     * @param role
     * @return
     */
    public PageBean list(PageBean pageBean, Role role) {
        return roleDao.list(pageBean, role);
    }

    /**
     * 根据id获取角色信息
     *
     * @param id
     * @return
     */
    public Role get(Integer id) {
        Role role = roleDao.findOne(id);
        role.setUnit(unitService.findOne(role.getUnit_id()));
        if (role.getData_scope() == Role.DataScope.ROLE_SET_UNIT) {
            List<Map<String, Object>> unitList = unitService.getUnitByRole(id);
            if (unitList != null && unitList.size() > 0) {
                for (int i = 0; i < unitList.size(); i++) {
                    role.setUnit_ids(role.getUnit_ids() + unitList.get(i).get("id").toString() + ",");
                }
            }
        }
        return role;
    }

    /**
     * 根据名称获取角色
     *
     * @param name
     * @return
     */
    public Role getByName(String name) {
        return roleDao.getByName(name);
    }

    /**
     * 根据英文名称获取角色
     *
     * @param en_name
     * @return
     */
    public Role getByEnName(String en_name) {
        return roleDao.getByEnName(en_name);
    }

    /**
     * 添加角色
     *
     * @param role
     */
    @Transactional(readOnly = false)
    public void addRole(Role role) {
        Role ori = getByName(role.getName());
        if (ori != null) {
            throw new BusinessException("登录名已存在");
        }
        ori = getByEnName(role.getName_en());
        if (ori != null) {
            throw new BusinessException("英文名已存在");
        }
        role.setCreator(UserUtils.getUser().getId());
        role.setCreate_time(new Date());
        role.setStatus(GlobalValue.AVAILABLE);
        role.setIs_del(GlobalValue.NO);
        role = roleDao.save(role);
        if (role.getData_scope() == Role.DataScope.ROLE_SET_UNIT) {
            String unit_ids = role.getUnit_ids();
            String[] idArray = unit_ids.split(",");
            if (StringUtil.isEmpty(unit_ids) || idArray == null || idArray.length <= 0) {
                throw new BusinessException("角色数据范围明细不能为空");
            }
            for (String idStr : idArray) {
                Integer unit_id = Integer.parseInt(idStr);
                roleDao.insertRoleUnit(role.getId(), unit_id);
            }
        }
        CacheUtils.removeAll(UserUtils.USER_CACHE);
    }

    /**
     * 编辑角色
     *
     * @param role
     * @return
     */
    @Transactional(readOnly = false)
    public int editRole(Role role) {
        Role ori = getByName(role.getName());
        if (ori != null && ori.getId() != role.getId()) {
            throw new BusinessException("登录名已存在");
        }
        ori = getByEnName(role.getName_en());
        if (ori != null && ori.getId() != role.getId()) {
            throw new BusinessException("英文名已存在");
        }
        if (role.getData_scope() != null && role.getData_scope() == Role.DataScope.ROLE_SET_UNIT) {
            roleDao.deleteRoleUnit(role.getId());
            String unit_ids = role.getUnit_ids();
            String[] idArray = unit_ids.split(",");
            if (StringUtil.isEmpty(unit_ids) || idArray == null || idArray.length <= 0) {
                throw new BusinessException("角色数据范围明细不能为空");
            }
            for (String idStr : idArray) {
                Integer unit_id = Integer.parseInt(idStr);
                roleDao.insertRoleUnit(role.getId(), unit_id);
            }
        }
        CacheUtils.removeAll(UserUtils.USER_CACHE);
        role.setUpdater(UserUtils.getUser().getId());
        role.setUpdate_time(new Date());
        return roleDao.updateRole(role);
    }

    /**
     * 删除角色
     *
     * @param idArray
     */
    @Transactional(readOnly = false)
    public void deleteRole(String[] idArray) {
        if (idArray != null && idArray.length > 0) {
            for (String idStr : idArray) {
                Integer id = Integer.parseInt(idStr);
                //删除角色id对应的用户
                roleDao.deleteUserRole(id);
                //删除角色id对应的用户
                roleDao.deleteRoleMenu(id);
                //删除角色id对应的部门
                roleDao.deleteRoleUnit(id);
                roleDao.deleteRole(id);
            }
        }
        CacheUtils.removeAll(UserUtils.USER_CACHE);
    }

    /**
     * 设置角色用户
     *
     * @param role_id
     * @param user_ids
     */
    @Transactional(readOnly = false)
    public void setRoleUser(Integer role_id, String user_ids) {
        String userArray[] = user_ids.split(",");
        //删除角色id对应的用户
        roleDao.deleteUserRole(role_id);
        if (userArray != null && userArray.length > 0) {
            for (int i = 0; i < userArray.length; i++) {
                if(!StringUtil.isEmpty(userArray[i])) {
                    Integer user_id = Integer.valueOf(userArray[i]);
                    roleDao.insertUserRole(role_id, user_id);
                }
            }
        }
        CacheUtils.removeAll(UserUtils.USER_CACHE);
    }

    /**
     * 设置角色用户
     *
     * @param role_id
     * @param user_id
     */
    @Transactional(readOnly = false)
    public void insertUserRole(Integer role_id, Integer user_id) {
        roleDao.insertUserRole(role_id, user_id);
    }


    @Transactional(readOnly = false)
    public void updateUserRole(Integer role_id, Integer user_id) {
        roleDao.delUserRoleByUser(user_id);
        roleDao.insertUserRole(role_id, user_id);
    }
    /**
     * 设置角色菜单
     *
     * @param role_id
     * @param menu_ids
     */
    @Transactional(readOnly = false)
    public void setRoleMenu(Integer role_id, String menu_ids) {
        String menuArray[] = menu_ids.split(",");
        //删除角色id对应的用户
        roleDao.deleteRoleMenu(role_id);
        if (menuArray != null && menuArray.length > 0) {
            for (int i = 0; i < menuArray.length; i++) {
                Integer user_id = Integer.valueOf(menuArray[i]);
                roleDao.insertRoleMenu(role_id, user_id);
            }
        }
        CacheUtils.removeAll(UserUtils.USER_CACHE);
    }

    /**
     * 新增角色菜单
     *
     * @param role_id
     * @param menu_id
     */
    @Transactional(readOnly = false)
    public void insertRoleMenu(Integer role_id, Integer menu_id) {
        roleDao.insertRoleMenu(role_id, menu_id);
    }

}
